package com.xiaoshuidi.cloud.module.iot.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Sky
 * create 2019/04/11
 * email sky.li@ixiaoshuidi.com
 * 调用第三方获取access_token工厂类封装
 **/
@Component("thirdInstanceFactory")
public class ThirdInstanceFactory implements ApplicationContextAware {

    private final static Logger LOGGER = LoggerFactory.getLogger(ThirdInstanceFactory.class);

    private static Map<String, ThirdInstanceService> thirdInstanceServiceMap;


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, ThirdInstanceService> map = applicationContext.getBeansOfType(ThirdInstanceService.class);
        thirdInstanceServiceMap = new HashMap<>();
        for (Map.Entry<String, ThirdInstanceService> entryMap : map.entrySet()) {
            ThirdInstanceService value = entryMap.getValue();
            String brandNo = value.getBrand();
            String[] brandNoArray = brandNo.split(",");
            for (String brand : brandNoArray) {
                thirdInstanceServiceMap.put(brand, value);
            }
        }
    }

    /**
     * 生产第三方获取工厂实例
     *
     * @param brand
     * @return
     */
    public static <T extends ThirdInstanceService> T produce(String brand) {
        return (T) thirdInstanceServiceMap.get(brand);
    }


}
